package utils
import (
	"encoding/pem"
	"fmt"
	"bytes"
	"strings"
	"crypto/x509"
	"github.com/hyperledger/fabric/core/chaincode/shim"
)
func GetCreatorName(stub shim.ChaincodeStubInterface)(string,error){
	name,err:=GetCreator(stub)
	if err!=nil{
		return "",err
	}
	memberName:=name[(strings.Index(name,"@")+1):strings.LastIndex(name,".example.com")]
	return memberName,nil
}
func GetCreator(stub shim.ChaincodeStubInterface)(string,error){
	creatorByte,_:=stub.GetCreator()
	certStart:=bytes.IndexAny(creatorByte,"-----BEGIN")
	if certStart==-1{
		fmt.Errorf("No cretificate found")
	}
	certText:=creatorByte[certStart:]
	bl,_:=pem.Decode(certText)
	if bl==nil{
		fmt.Errorf("Could not decode the PEM structure")
	}
	cert,err:=x509.ParseCertificate(bl.Bytes)
	if err!=nil{
		fmt.Errorf("ParseCertificate failed")
	}
	uname:=cert.Subject.CommonName
	return uname,nil
}